import java.nio.ByteBuffer;
import java.net.*;

public class RunTestMcast {

	public static void main (String[] args) {
//		System.out.println("args.length: " + args.length);
		Com s = new Com(6666,"230.1.1.66");
		
		if(args.length < 2 || args.length > 6 ){
			usage();
			System.exit(1);
		}
		
		String name = args[1];
		
		//pre-process name
		if(name.length()<6){
			name += "******"; //add until length=6
			name = name.substring(0, 6);			
		}else if(name.length() > 6){
			name = name.substring(0, 6);			
		}
//		System.out.println("after preprocess name=" + name + " " + name.length());
		
		Thread receiver;
		try {
			receiver = new ReceiverThread(s, name);
			receiver.start();
		} catch (SocketException e) {
			e.printStackTrace();
		}
		
		InetAddress moi;
		try	{ 
			moi = InetAddress.getLocalHost();
		} catch (UnknownHostException ex){ 
			moi=null;
		}
		
		if(!name.equals("Listen")){

			short beginSeq = 0;
			
			if(args.length >= 4){
				beginSeq = (short)Integer.parseInt(args[3]);
			}
			
			short seq = beginSeq;
			
			short endSeq = 100; //maximum 100 packets
			
			if(args.length == 6){
				endSeq = (short)Integer.parseInt(args[5]);
			}
//			System.out.println("beginSeq=" + beginSeq + " endSeq=" + endSeq);
			//sending process
			while(seq <= endSeq){
				
//				String msgContent = "envoi de "+ moi.getHostAddress() + " hello_" + seq; ;
				String msgContent = "hello_" + seq; ;
				MyMessage msg = new MyMessage(name, seq, msgContent);
				s.send(msg.getBuf());
				
				seq++;
				
				if(seq > endSeq){
					System.out.println("Send done at endSeq=" + endSeq);
					break; //while
				}
				
				try {
				    Thread.sleep((long)(Math.random() * 1000));
				} catch (InterruptedException e) { }
				
			}//while(true)
		}
		else{
			ByteBuffer b = ByteBuffer.allocate(1400) ;
//			short seq = 0;
			String msgContent = "inittttt";
			MyMessage msg = new MyMessage((short)0,name, (short)0, msgContent);
			b = msg.getBuf();
			s.send (b);
		}
	}
	
	public static void usage(){
		System.err.println("Usage: java -jar mcast.jar -s <Sender> [-b beginSequenceNumber] [-e endSequenceNumber]");
	}
}
